/**
 * @brief: 获取单片机的UID
 */
#include "mcu_uid.h"
#include "md5.h"


char dev_derial_num[DEV_SERIAL_NUM_LEN] = {0}; // 设备序列号


/**
 *  @brief  将经过MD5计算后的UID取16位大写，转为字符串
 *  @param  经过MD5变换后的UID
 *  @retval 无
 */
void mcu_md5_uid_hex_to_str(uint8_t *md5_uid)
{
    int i;
    char temp;
    
    for(i=0; i<DEV_SERIAL_NUM_LEN/2; ++i)
    {
        temp = (md5_uid[4+i]>>4) & 0x0F;
        if(temp >= 10)
            dev_derial_num[2 * i] = temp - 10 + 'A';
        else
            dev_derial_num[2 * i] = temp + '0';
    
        temp = md5_uid[4+i] & 0x0F;
        if(temp >= 10)
            dev_derial_num[2 * i + 1] = temp - 10 + 'A';
        else
            dev_derial_num[2 * i + 1] = temp + '0';
    }
}



/**
 *  @brief  获取MCU的UID标识符
 *  @param  无
 *  @retval 无
 */
void get_mcu_uid(void)
{
    uint32_t temp0, temp1, temp2;
    uint8_t original_uid[12] = {0}; // 原始ID 96Bits
    uint8_t md5_str[MD5_SIZE];
    int32_t md5_str_len;
    
    temp0 = *(volatile uint32_t*)(DEVICE_ID_BASE_ADDR); //产品唯一身份标识寄存器（96位）
    temp1 = *(volatile uint32_t*)(DEVICE_ID_BASE_ADDR+4);
    temp2 = *(volatile uint32_t*)(DEVICE_ID_BASE_ADDR+8);
    
    original_uid[0]  = (uint8_t)( temp0 & 0x000000FF);
    original_uid[1]  = (uint8_t)((temp0 & 0x0000FF00)>>8);
    original_uid[2]  = (uint8_t)((temp0 & 0x00FF0000)>>16);
    original_uid[3]  = (uint8_t)((temp0 & 0xFF000000)>>24);
    original_uid[4]  = (uint8_t)( temp1 & 0x000000FF);
    original_uid[5]  = (uint8_t)((temp1 & 0x0000FF00)>>8);
    original_uid[6]  = (uint8_t)((temp1 & 0x00FF0000)>>16);
    original_uid[7]  = (uint8_t)((temp1 & 0xFF000000)>>24);
    original_uid[8]  = (uint8_t)( temp2 & 0x000000FF);
    original_uid[9]  = (uint8_t)((temp2 & 0x0000FF00)>>8);  
    original_uid[10] = (uint8_t)((temp2 & 0x00FF0000)>>16);
    original_uid[11] = (uint8_t)((temp2 & 0xFF000000)>>24);
    
    compute_string_md5(original_uid, sizeof(original_uid)/sizeof(original_uid[0]), md5_str);
    mcu_md5_uid_hex_to_str(md5_str);
}




/**
 *  @brief  超时判断
 *  @param  上个状态记录的时间戳 systick
 *  @param  超时时间
 *  @retval 超时返回true，不超时返回false
 */
bool is_it_timeout(uint32_t pre_tick, uint32_t timeout_ms)
{
//    uint32_t curr_tick = HAL_GetTick();
//    
//    if( curr_tick >= pre_tick)
//    {
//        if(curr_tick - pre_tick >= timeout_ms)
//            return true;
//        else
//            return false;
//    }
//    else
//    {
//        if(curr_tick + (~pre_tick) >= timeout_ms)
//            return true;
//        else
//            return false;
//    }
}